<template>
	<view class="assetApply">
		<view class="applyHead">
			<view>
				<picker @change="bindPickerChange" :value="pickerIndex" :range="array"
					:disabled="allData.assetApplyId != null">
					<view class="select-shop">{{applyUnitName}}
						<view class="v-m right">▾</view>
					</view>
				</picker>
			</view>
			<view>
				<button class="addbtn " @click="openForm"><text
						class="iconfont icon-xinzeng"></text>&nbsp;&nbsp;添加</button>
			</view>
		</view>

		<view class="assetList">
			<view v-if="listData.length==0" class="no-list">请添加申领数据！</view>
			<view class="assetListItem" v-for="(item,index) in listData">
				<uni-swipe-action-item>
					<view>
						<view class="itemHeadTitle">{{item.assetName}}</view>
						<view class="itemContent">
							<view class="conCenter">
								<view>规格类型：{{item.assetTypeName}}</view>
								<view>规格型号：{{item.specification}}</view>
								<view>申请数量：{{item.applyQty}}</view>
								<!-- <view>期望日期：{{item.applyExpectDate}}</view> -->
							</view>
						</view>
					</view>
					<template v-slot:right>
						<view class="right-icon-edit" @click="toEdit(index)">
							<uni-icons type="compose" size="30" color='#fff'></uni-icons>
							<view>编辑</view>
						</view>
						<view class="right-icon" @click="toDel(index)">
							<uni-icons type="trash" size="30" color='#fff'></uni-icons>
							<view>删除</view>
						</view>
					</template>
				</uni-swipe-action-item>
			</view>
		</view>

		<!-- <view class="applyMarks">
			<h2>申请说明：</h2>
			<textarea cols="30" rows="10" v-model="allData.remarks"></textarea>
		</view> -->

		<view class="bottom-btn">
			<button class="toQR " @click="inputDialogToggle"><text
					class="iconfont icon-jsontijiao"></text>&nbsp;&nbsp;提交</button>
		</view>

	</view>
	<!-- 底部弹窗 -->
	<uni-popup ref="popupRef" type="bottom">
		<view class="formMain">
			<h3>添加资产</h3>
			<uni-forms ref="formRef" :modelValue="formData" :rules="rules" label-position="top" label-width="100">
				<uni-forms-item label="资产名称" name="assetName" required>
					<uni-easyinput type="text" v-model="formData.assetName" placeholder="" />
				</uni-forms-item>
				<uni-forms-item label="资产类型" name="assetType" required>
					<!-- <uni-easyinput type="text" v-model="formData.assetType" placeholder="" /> -->
					<uni-data-select v-model="formData.assetType" :localdata="assetTypeOpt" @change="assetTypeChange"
						class="form-sel"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="规格型号" name="specification">
					<uni-easyinput type="text" v-model="formData.specification" placeholder="" />
				</uni-forms-item>
				<uni-forms-item label="申请数量" name="applyQty" required>
					<uni-easyinput type="text" v-model="formData.applyQty" placeholder="" />
				</uni-forms-item>
				<!-- <uni-forms-item label="期望日期" name="applyExpectDate" required>
					<uni-datetime-picker type="date" v-model="formData.applyExpectDate" @change="changeDate"
						:start="startDate" />
				</uni-forms-item> -->
			</uni-forms>
			<button @click="submit" class="popbtn color-g-bg">确认添加</button>
		</view>
	</uni-popup>

	<uni-popup ref="inputDialogRef" type="dialog">
		<uni-popup-dialog ref="inputClose" mode="input" title="申请备注" value="" placeholder="请输入内容"
			@confirm="dialogInputConfirm"></uni-popup-dialog>
	</uni-popup>

	<MessageTip ref="messageTip" :tipContent="tipContent" @clickType="handleShowOrHideTip" />

</template>

<script lang="ts" setup>
	import {
		reactive,
		ref,
		nextTick
	} from 'vue'
	import {
		submitApply,
		editApply
	} from '@/common/api/assetAPI.ts'
	import {
		getPosition,
		workflowList
	} from '@/common/api/comAPI.ts'
	import {
		applyDetail,
		assetType,
		getNumber_api
	} from '@/common/api/assetAPI.ts'
	import {
		onLoad
	} from "@dcloudio/uni-app";
	const tipContent = ref('') //提示信息
	const messageTip = ref()

	const array = ref(['请选择店铺']),
		pickerIndex = ref(0);
	const currentTab = ref(0)
	const applyUnitName = ref('请选择店铺');
	const popupRef = ref(),
		inputDialogRef = ref();
	const formRef = ref();
	const startDate = ref((new Date()).getTime());
	const sourceData = ref([]),
		sourceIds = ref([]);
	const applyInfo = ref({});
	const editIndex = ref(null);
	const applyExpectDate = ref();

	onLoad((parm) => {
		console.log('parm', parm)
		if (parm.assetApplyId) {
			allData.value.assetApplyId = parm.assetApplyId;
			getDetail(parm.assetApplyId)
		}
	})
	// 全部提交总数据
	const allData = ref({
		assetApplyId: null,
		assetApplyNo: null,
		applyUnits: null,
		assetApplyType: 1,
		remarks: null,
		dtls: [],
	})
	if (!allData.value.assetApplyNo) {
		getNumber_api({
			enumValue: 'SQ'
		}).then(res => {
			if (res.code == 0) {
				allData.value.assetApplyNo = res.data
			}
		})
	}

	const poss = ref([])
	getPosition().then(value => {
		poss.value = value.data.records
		value.data.records.forEach(item => {
			array.value.push(item.storeName)
		})
	});
	const assetTypeOpt = ref([]);
	assetType().then(res => {
		// console.log('资产类型',res)
		let list: any = res.data;
		list.forEach(em => {
			em.value = em.sysEnumId;
			em.text = em.enumName;
			assetTypeOpt.value.push(em);
		})
	});
	const assetTypeChange = (e) => {
		// console.log(e);
		assetTypeOpt.value.forEach(em => {
			if (em.value === e) {
				formData.assetTypeName = em.text;
			}
		})
	};
	const bindPickerChange = (e) => {
		applyUnitName.value = array.value[e.detail.value];
		pickerIndex.value = e.detail.value;
		// value
		try {
			allData.value.applyUnits = poss.value[e.detail.value - 1].id
		} catch (e) {
			//TODO handle the exception
			console.log('没有选位置')
			allData.value.applyUnits = null
		}

	}
	// 显示数据
	const listData = ref([])
	// 表单数据
	let formData = reactive({
		assetApplyId: null,
		applySort: null,
		assetName: null,
		specification: null,
		applyQty: null,
		assetType: null,
		assetTypeName: null,
		// applyExpectDate: '2021-04-3', //期望日期
	})

	function getDetail(assetApplyId) {
		applyDetail(assetApplyId).then((res: any) => {
			listData.value = res.data.dtls;
			allData.value.applyUnits = res.data.applyUnits;
			applyInfo.value = res.data;
			applyUnitName.value = res.data.applyUnitName;
			res.data.dtls.forEach(em => {
				sourceData.value.push(Object.assign({}, em));
				sourceIds.value.push(em.assetApplyId);
			})
		})
	}

	let xuhao = 1
	// 表单验证
	const rules = {
		assetName: {
			rules: [{
				required: true,
				maxLength: 50,
				errorMessage: '必填且不大于50个字符'
			}]
		},
		// specification: {
		// 	rules: [{
		// 		required: true,
		// 		maxLength: 50,
		// 		errorMessage: '必填且不大于50个字符'
		// 	}]
		// },
		assetType: {
			rules: [{
				required: true,
				maxLength: 50,
				errorMessage: '请选择资产类型'
			}]
		},
		// applyExpectDate: {
		// 	rules: [{
		// 		required: true,
		// 		errorMessage: '请选日期'
		// 	}]
		// },
		applyQty: {
			rules: [{
				maxLength: 50,
				required: true,
				errorMessage: '必填且为数字'
			}, {
				format: 'number',
				errorMessage: '请输入数字'
			}]
		}
	}

	const inputDialogToggle = () => {
		inputDialogRef.value.open()
	};

	//最后提交
	const dialogInputConfirm = (val) => {
		allData.value.remarks = val;
		//提交
		submitBtn();
	};

	// 表单提交
	const submit = () => {
		formRef.value.validate().then(res => {
			if (editIndex.value != null) {
				listData.value[editIndex.value].assetName = formData.assetName;
				listData.value[editIndex.value].specification = formData.specification;
				listData.value[editIndex.value].applyQty = formData.applyQty;
				listData.value[editIndex.value].assetType = formData.assetType;
				listData.value[editIndex.value].assetTypeName = formData.assetTypeName;
				// listData.value[editIndex.value].applyExpectDate = formData.applyExpectDate;
			} else {
				listData.value.push({
					assetName: res.assetName,
					specification: res.specification,
					applyQty: res.applyQty,
					assetType: res.assetType,
					assetTypeName: formData.assetTypeName,
				})
				// applyExpectDate: formData.applyExpectDate
			}

			for (let i in formData) {
				formData[i] = null
			}
			popupRef.value.close()
		}).catch(err => {
			console.log('表单错误信息：', err);
		})
	}
	const openForm = () => {
		if (allData.value.applyUnits == null) {
			uni.showToast({
				title: '请先选择位置',
				icon: 'none'
			});
			return
		}
		for (let i in formData) {
			formData[i] = null
		}
		editIndex.value = null;
		popupRef.value.open();
	}
	//编辑
	const toEdit = (index) => {
		editIndex.value = index;
		formData.assetApplyId = listData.value[index].assetApplyId;
		// formData.applyExpectDate = listData.value[index].applyExpectDate;
		// applyExpectDate.value = listData.value[index].applyExpectDate;
		formData.applyQty = listData.value[index].applyQty;
		formData.assetName = listData.value[index].assetName;
		formData.assetType = listData.value[index].assetType;
		formData.assetTypeName = listData.value[index].assetTypeName;
		formData.specification = listData.value[index].specification;
		// console.log('期望日期', formData.applyExpectDate);
		popupRef.value.open();
	}
	// 删除
	const delIndex = ref()
	const toDel = (index) => {
		tipContent.value = '确认删除吗？'
		delIndex.value = index
		messageTip.value.openTip()
	}
	// 清空
	const toClear = () => {
		tipContent.value = '确认清空吗？'
		messageTip.value.openTip()
	}
	// 提交按钮
	const submitBtn = () => {
		if (listData.value.length != 0) {
			allData.value.dtls = []
			listData.value.forEach((em: any, i) => {
				em.applySort = i + 1;
				allData.value.dtls.push(em);
			})
			tipContent.value = '确认提交申请吗？'
			messageTip.value.openTip()

		} else {
			uni.showToast({
				icon: 'error',
				title: '我需要一条数据再提交'
			});
		}
	};
	const handleShowOrHideTip = (type: string) => {
		if (type == 'yes') {
			if (tipContent.value == '确认删除吗？') {
				listData.value.splice(delIndex, 1)
			} else if (tipContent.value == '确认清空吗？') {
				listData.value = []
				xuhao = 0
			} else if (tipContent.value == '确认提交申请吗？') {
				if (applyInfo.value.assetApplyId) {
					//有值为编辑
					applyEditCommit();
				} else {
					//无值为新增
					submitApply(allData.value).then(value => {
						if (value.code == 0) {
							uni.showToast({
								title: value.message,
								icon: 'none',
								duration: 500
							});
							inputDialogRef.value.close();
							listData.value = []
							allData.value.remarks = null

							setTimeout(() => {
								uni.navigateBack({
									delta: 1
								})
								// uni.redirectTo({
								// 	url: '/pages/assets/assetReceive/index'
								// })
							}, 500)

						} else {
							uni.showToast({
								icon: 'none',
								title: value.message
							})
						}
					})
				}
			}

		}
	}
	const changeDate = (e) => {
		// formData.applyExpectDate = e;
		// applyExpectDate.value = e;
		console.log("-change事件:", formData.applyExpectDate);
	};

	//编辑提交
	function applyEditCommit() {
		let addList = [],
			ids = [],
			editAfter = [];
		listData.value.forEach(em => {
			if (em.assetApplyId) {
				ids.push(em.assetApplyId);
				editAfter.push(em);
			} else {
				em.operType = 2;
				addList.push(em); //新增的数据
			}
		});
		//删除的
		let detList = [],
			detIds = [];
		detIds = getArrDifference(ids, sourceIds.value);
		detIds.forEach((id) => {
			sourceData.value.forEach(em => {
				if (id === em.assetApplyId) {
					//删除的数据
					detList.push(Object.assign(em, {
						operType: 1
					}));
				}
			})
		})
		//编辑的
		let editList = [];
		editAfter.forEach(item => {
			sourceData.value.forEach(em => {
				if (item.assetApplyId === em.assetApplyId) {
					// console.log('进入对比',JSON.stringify(item))
					// console.log('进入对比',JSON.stringify(em))
					// item.applyExpectDate != em.applyExpectDate
					if (item.assetName != em.assetName ||
						item.specification != em.specification ||
						item.applyQty != em.applyQty ||
						item.assetType != em.assetType
					) {
						//编辑的数据
						editList.push(Object.assign(item, {
							operType: 3
						}));
					}
				}
			})
		})
		let del = [];
		del = editList.concat(addList).concat(detList);
		del.forEach((em, i) => {
			em.applySort = i + 1;
		})
		console.log('明细', del);
		applyInfo.value.dtls = del; //明细
		applyInfo.value.remarks = allData.value.remarks; //备注
		// return false;
		editApply(applyInfo.value).then(value => {
			if (value.code == 0) {
				uni.showToast({
					title: value.message,
					icon: 'none',
					duration: 500
				});
				inputDialogRef.value.close();
				listData.value = []
				allData.value.remarks = null
				setTimeout(() => {
					uni.navigateBack({
						delta: 1
					})
					// uni.redirectTo({
					// 	url: '/pages/assets/assetReceive/index'
					// })
				}, 500)

			} else {
				uni.showToast({
					icon: 'none',
					title: value.message
				})
			}
		})

	}
	/**
	 * 获取数组中不同的值
	 * @param arr1、
	 * @param arr2 两个不同的数组
	 * 返回 两个数组中不同值数组
	 * */
	function getArrDifference(arr1: Array < any > , arr2: Array < any > ) {
		//array.filter(function(currentValue,index,arr), thisValue)
		//currentValue,index,arr 当前元素的值，当前元素的索引，当前元素属于的数组对象
		// thisValue 对象作为该执行回调时使用，传递给函数，
		return arr1.concat(arr2).filter(function(v, i, arr) {
			//若下标相等则代表值为唯一值：为两数组的不同项
			return arr.indexOf(v) === arr.lastIndexOf(v);
		});
	};
</script>

<style scoped lang="scss">
	:deep(.uni-datetime-picker--btn) {
		background-color: #016751 !important;
	}

	:deep(.uni-calendar-item--checked) {
		background-color: #016751 !important;
	}

	.assetApply {
		height: 100%;
		background: #eee;
		overflow: auto;
	}

	.formMain {
		background-color: #fff;
		padding: 10px 30px;
		margin-top: 80px;
	}

	.formMain>h3 {
		color: #666;
		text-align: center;
		padding-bottom: 10px;
	}

	.applyHead {
		display: flex;
		flex-wrap: row nowrap;
		box-sizing: border-box;
		padding: 10px;

		.addbtn {
			display: inline-block;
			background-color: #016751;
			border-radius: 2px;
			color: #fff;
			line-height: 30px;
			font-size: 14px;
			padding: 0 10px;
			margin-top: 3px;
		}
	}

	.applyHead>view:first-child {
		width: 75%;
		line-height: 30px;
		background: #fff;
		padding: 3px 10px;
		vertical-align: middle;
		border-radius: 5px;
	}

	.applyHead>view:nth-child(2) {
		width: 25%;
		text-align: right;
		vertical-align: middle;
	}

	.applyMarks {
		padding: 0 15px 15px 15px;
	}

	.applyMarks h2 {
		color: #666;
	}

	.applyMarks textarea {
		background-color: #eee;
		margin-top: 15px;
		width: 100%;
		max-width: 100%;
	}

	.assetList {
		padding: 10px;
		background-color: #eee;
		height: calc(100% - 140px);
		overflow: auto;
	}

	.no-list {
		padding: 30px 0;
		text-align: center;
		color: #999;
	}

	.itemHead {
		position: relative;
	}

	.assetListItem {
		margin-top: 15px;
		background-color: #fff;
		border-radius: 5px;
	}

	.form-sel {
		display: block !important;
		padding: 0 !important;
	}

	.right-icon,
	.right-icon-edit {
		height: 100%;
		background-color: #dc143c;
		color: #fff;
		padding: 50px 20px;
		box-sizing: border-box;
		border-top-right-radius: 5px;
		border-bottom-right-radius: 5px;
	}

	.right-icon-edit {
		background-color: #ff9d02;
		border-top-right-radius: 0px;
		border-bottom-right-radius: 0px;
	}

	.assetListItem:first-child {
		margin-top: 0;
	}

	.itemHeadTitle {
		padding: 10px 25px;
		font-weight: bold;
		color: #333;
		border-bottom: 1px solid #ddd;
	}

	.itemContent {
		font-size: 14px;
		box-sizing: border-box;
		padding: 10px;
		display: flex;
		flex-wrap: row nowrap;
	}

	.itemContent>view:nth-child(1) {
		width: 85%;
		padding-left: 15px;
		color: #333;
	}

	.itemContent>view:nth-child(1)>view {
		padding: 3px 0;
		text-overflow: ellipsis;
		white-space: nowrap;
		overflow: hidden;
		cursor: pointer;
	}

	.itemContent>view:nth-child(2) {
		width: 15%;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.itemHand {
		padding: 15px;
		display: flex;
		justify-content: flex-end;
	}

	.itemHand>view {
		padding: 4px 23px;
		font-size: 12px;
		border-radius: 5px;
		border: 1px solid #369;
		color: #369;
		margin-right: 8px;
	}

	.popbtn {
		width: 60%;
		border-radius: 30px;
		line-height: 30px;
		font-size: 14px;
	}
</style>
